﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using kysec.RAL.EFToMySql;

namespace kysec.Bll.Message
{
    /// <summary>
    /// 查找留言类
    /// </summary>
    public class Search
    {
        /// <summary>
        /// 找出所有的留言，按时间顺序排列
        /// </summary>
        /// <param name="typeId">0：客户反馈 1：留言薄</param>
        /// <param name="type">true：已回复 false：未回复</param>
        /// <param name="takeitem">每页显示的条数</param>
        /// <param name="page">跳过几页</param>
        /// <returns>返回找到的列表</returns>
        public static List<tb_message> getReplayMsg(int typeId, int type, int takeitem, int page)
        {
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
                          .RetrieveObject(string.Format("getMsg_{0}_{1}_{2}", type
                           , page, takeitem));
            bool typeNumber = false;
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();

                //找出所有的留言信息
                var str = from c in ctx.tb_message
                          where c.c_b_isDelete == false && c.c_i_typeId == typeId
                          orderby c.c_dt_publishedTime descending
                          select c;

                //找出是否已被操作的留言信息：true：已回复 和 false：未回复
                if (type != null)
                {
                    typeNumber = type == 0 ? false : true;
                    str = from c in ctx.tb_message
                          where c.c_b_isDelete == false && c.c_b_isReplay == typeNumber && c.c_i_typeId == typeId
                          orderby c.c_dt_publishedTime descending
                          select c;
                }

                var list = (str).Skip(takeitem * page)
                             .Take(takeitem)
                             .ToList();
                ctx.Dispose();
                if (list.Any())
                {
                    kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                      .AddObjectWithAbsoluteTime(string.Format("getMsg_{0}_{1}_{2}", type, page, takeitem)
                      , list,
                      10000
                      , System.Web.Caching.CacheItemPriority.Normal);
                    return list;
                }
                return new List<tb_message>();
            }
            return (List<tb_message>)o;
        }

        /// <summary>
        /// 得到具体的某一条信息的留言
        /// </summary>
        /// <param name="id">留言Id</param>
        /// <param name="type">类型：0：客户反馈 1：留言薄</param>
        /// <returns>返回找到的信息</returns>
        public static List<tb_message> getMsg(string id, int type)
        {
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            try
            {
                id = kysec.CR.Common.EncodeByBase64.Decode(id);
                var list = ctx.tb_message.Where(c => c.c_i_typeId == type && c.c_uq_mId.Equals(id)).ToList();

                if (list.Count == 0)
                {
                    return new List<tb_message>();
                }

                return list;

            }
            catch (Exception ex)
            {
                kysec.CR.Logger.MyLogger.Error(typeof(message), "查找具体的某一条留言时出错！\t" + ex.ToString());
            }
            finally { ctx.Dispose(); }
            return new List<tb_message>();
        }

        /// <summary>
        /// 得到具体的某一类信息的留言，用于前台页面中的显示
        /// </summary>
        /// <param name="id">留言Id</param>
        /// <param name="type">类型：0：客户反馈 1：留言薄</param>
        /// <returns>返回找到的信息</returns>
        public static List<kysec.RAL.EFToMySql.vw_msg_repmsg> getMsgForpre(int type,int takeitem,int page)
        {
             var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().RetrieveObject(
                string.Format("getMsgForpre_{0}", type + DateTime.Now.Second));
             if (o == null)
             {
                 MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                 try
                 {
                     var list = ctx.vw_msg_repmsg.Where(c => c.c_i_typeId == type).Skip(page).Take(takeitem).ToList();

                     if (list.Count == 0)
                     {
                         return new List<kysec.RAL.EFToMySql.vw_msg_repmsg>();
                     }
                     kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity().AddObjectWithAbsoluteTime(
                                 string.Format("getMsgForpre_{0}", type + DateTime.Now.Second),
                                 list,
                                 10000,
                                 System.Web.Caching.CacheItemPriority.Normal);
                     return list;

                 }
                 catch (Exception ex)
                 {
                     kysec.CR.Logger.MyLogger.Error(typeof(message), "查找具体的某一类留言时出错！\t" + ex.ToString());
                 }
                 finally { ctx.Dispose(); }
             }
            return (List<kysec.RAL.EFToMySql.vw_msg_repmsg>)o;
        }
    }

    /// <summary>
    /// 对留言的操作类
    /// </summary>
    public class message
    {
        /// <summary>
        /// 添加留言信息，返回成功信息
        /// </summary>
        /// <param name="model">数据集</param>
        /// <returns>0：添加失败 1：添加成功 2：添加异常</returns>
        public static string AddMessage(int type,tb_message model)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            Guid mId = Guid.NewGuid();
            try
            {
                tb_message message = new tb_message
                {
                    c_uq_mId = mId.ToString(),
                    c_vc_title = model.c_vc_title,
                    c_i_typeId = type,
                    c_vc_company = model.c_vc_company,
                    c_dt_publishedTime = DateTime.Now,
                    c_ntx_content = model.c_ntx_content,
                    c_vc_emial = model.c_vc_emial,
                    c_vc_fax = model.c_vc_fax,//传真
                    c_vc_name = model.c_vc_name,
                    c_vc_phone = model.c_vc_phone,
                    c_b_isReplay = false,
                    c_b_isDelete = false
                };
                ctx.AddObject("tb_message", message);
                if (msg_replay.AddReplayMsg(mId).Equals("1"))
                {
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t插入留言信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }



        /// <summary>
        /// 删除留言信息，可以同时恢复删除的新闻
        /// </summary>
        /// <param name="newsId">需要删除的新闻信息的Id</param>
        /// <returns>0：没有找到信息或删除失败 1：删除成功 2：删除异常</returns>
        public static string DeleteMessage(string id)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            try
            {
                id = kysec.CR.Common.EncodeByBase64.Decode(id);
                var list = ctx.tb_message.Where(c => c.c_uq_mId.Equals(id)).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_b_isDelete)
                            item.c_b_isDelete = false;
                        else
                            item.c_b_isDelete = true;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t删除留言信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(message), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

    }
}
